package com.wang.mandkey.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

import com.wang.mandkey.net.ScreenProviderThread;
import com.wang.mandkey.net.ServerThread;
import com.wang.mandkey.tool.Tool;
import com.wang.mandkey.utils.ProjectEnvironment;
import com.wang.mandkey.utils.StringUtils;

/**
 * 主页面
 * @author Administrator
 *
 */
public class MainFrame extends JFrame {

	private JLabel jLabelip;
	private JLabel jLabelPort;
	private JComboBox jcomBoBoxIps;
	private JTextField jTextFieldPort, jTextFieldImgPort;
	private JPanel jPanelIp, jPanelSetting, jBottomPanel;
	private JPanel jPanelContent;
	private JButton jButtonStart, jButtonStop;
	private ServerThread serverThread;
	private JMenuBar menuBar;
	private String title = "无线鼠盘";
	private String company = "@猫哥:qq 382758656";
	private static TrayIcon trayicon;
	private boolean isTray = false;
	private ScreenProviderThread sct = null;
	private JTextArea jta;
	private JScrollPane jsp = new JScrollPane();

	public MainFrame() {

		setTitle("无线鼠盘-PC端v1.3.0.0");
		setLayout(new BorderLayout());
		setUpView();
		Dimension sc = Tool.getScreenDimen();

		setBounds(sc.width - 400, 300, 400, 400);
		Dimension dimen = new Dimension(400, 400);
		setMinimumSize(dimen);

		setVisible(true);
		invalidate();
		setAlwaysOnTop(true);
		setIconImage(Toolkit.getDefaultToolkit().createImage(
				MainFrame.class.getResource("res/icons/icon.png")));
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				SystemTrayInitial();
			}
		});
	}

	/**
	 * 初始化视图
	 */
	protected void setUpView() {

		jPanelContent = new JPanel();
		jPanelContent.setBorder(new LineBorder(Color.black, 1));
		jPanelIp = new JPanel();
		jLabelip = new JLabel("本机地址:");
		jLabelip.setToolTipText("ip超过2个，请逐个测试!");

		jLabelPort = new JLabel("命令端口:");
		jButtonStart = new JButton("开始");
		jButtonStop = new JButton("停止");
		jButtonStop.setEnabled(false);

		JPanel progressBarPanel = new JPanel(new BorderLayout());
		jta = new JTextArea();
		jta.setBorder(new LineBorder(Color.BLACK, 1));

		jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		jsp.setViewportView(jta);
		jsp.setEnabled(true);
		jsp.setAutoscrolls(true);
		progressBarPanel.add(jsp, BorderLayout.CENTER);
		Document doc = jta.getDocument();
		doc.addDocumentListener(new DocumentListener() {
			@Override
			public void removeUpdate(DocumentEvent e) {

			}

			@Override
			public void insertUpdate(DocumentEvent e) {

			}

			@Override
			public void changedUpdate(DocumentEvent e) {

			}
		});

		jButtonStart.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				jButtonStop.setEnabled(true);
				jButtonStart.setEnabled(false);
				
				String portStr = jTextFieldPort.getText();
				
				int port = ProjectEnvironment.INT_DEFAULT_PORT_COMMAND;
				String imagePort = jTextFieldImgPort.getText();

				if (!StringUtils.isEmpty(portStr)
						&& !StringUtils.isEmpty(imagePort)) {
					try {
						ProjectEnvironment.INT_DEFAULT_PORT_IMG = Integer
								.parseInt(imagePort);
						port = Integer.parseInt(portStr);
					} catch (NumberFormatException e1) {
						e1.printStackTrace();
					}

				}
				if (serverThread != null) {
					serverThread.killSelf();
				}
				
				Object ip = jcomBoBoxIps.getSelectedItem();
				InetAddress inetAddress=null;
				try {
					inetAddress = InetAddress.getByName(ip.toString());
				} catch (UnknownHostException e1) {
					e1.printStackTrace();
				}
				serverThread = new ServerThread(inetAddress,port, jta);
				serverThread.StartMe();

				sct = new ScreenProviderThread(jta);

			}
		});
		jButtonStop.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				jButtonStart.setEnabled(true);
				jButtonStop.setEnabled(false);
				serverThread.killSelf();
				if (null != sct) {
					sct.killSelf();
				}
			}
		});

		jTextFieldPort = new JTextField(String
				.valueOf(ProjectEnvironment.INT_DEFAULT_PORT_COMMAND), 5);

		
		
		jcomBoBoxIps = new JComboBox(Tool.getLocalIp());

		jPanelContent.setLayout(new BorderLayout());

		jPanelIp.setLayout(new FlowLayout(FlowLayout.LEFT));
		jPanelIp.add(jLabelip);
		jPanelIp.add(jcomBoBoxIps);

		JPanel portPanel = new JPanel();
		portPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		portPanel.add(jLabelPort);
		portPanel.add(jTextFieldPort);

		jPanelContent.add(jPanelIp, BorderLayout.NORTH);// 添加第一行设置项
		jPanelContent.add(portPanel, BorderLayout.CENTER);
		jPanelSetting = new JPanel();// 系统设置的Panel

		jPanelSetting.setLayout(new BorderLayout());
		jPanelSetting.setBorder(new LineBorder(Color.black, 1));
		JPanel portPanelscreen = new JPanel();
		portPanelscreen.setLayout(new FlowLayout(FlowLayout.LEFT));
		jTextFieldImgPort = new JTextField(String
				.valueOf(ProjectEnvironment.INT_DEFAULT_PORT_IMG), 5);// 图片发送端口
		portPanelscreen.add(new JLabel("截屏端口:"));
		portPanelscreen.add(jTextFieldImgPort);
		jPanelSetting.add(portPanelscreen, BorderLayout.NORTH);


		jPanelSetting.add(progressBarPanel, BorderLayout.CENTER);

		jBottomPanel = new JPanel();
		jBottomPanel.setBorder(new LineBorder(Color.black, 1));
		jBottomPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
		jBottomPanel.add(jButtonStart);
		jBottomPanel.add(jButtonStop);

		add(jPanelContent, BorderLayout.NORTH);
		add(jPanelSetting, BorderLayout.CENTER);
		add(jBottomPanel, BorderLayout.SOUTH);

		menuBar = new JMenuBar();
		String str[] = { "文件", "帮助" };
		for (int i = 0; i < str.length; i++) {

			JMenu jmenu = new JMenu(str[i]);
			if (i == 0) {

				JMenuItem jmenuItemIcon = new JMenuItem("程序托盘");
				jmenu.add(jmenuItemIcon);
				jmenuItemIcon.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						if (isTray) {
							setVisible(false);
						} else {
							setVisible(false);
							SystemTrayInitial();

						}
					}
				});

				JMenuItem jmenuItemExit = new JMenuItem("退出程序");
				jmenu.add(jmenuItemExit);
				jmenuItemExit.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						System.exit(0);
					}
				});

			}
			if (i == 1) {
				JMenuItem jmenuItemHelp = new JMenuItem("如何使用");
				jmenu.add(jmenuItemHelp);
				jmenuItemHelp.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						JOptionPane.showMessageDialog(null,
								"1,保证android手机和pc连接到同一个路由器下。\n"
										+ "2,移动鼠标或者使用自定义键盘时请先按手机的menu键锁定键。\n"
										+ "3,如果你的笔记本电脑是win7系统可以百度一下如何共享wifi。");

					}
				});

				JMenuItem jmenuItemAbout = new JMenuItem("关于鼠盘");
				jmenu.add(jmenuItemAbout);
				jmenuItemAbout.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {

						JOptionPane.showMessageDialog(null,
								" 作者保留版权!联系邮件:wzyfly@sina.com");
					}
				});
			}

			menuBar.add(jmenu);
		}
		setJMenuBar(menuBar);
		validate();
	}

	private PopupMenu createMenu() { // 创建系统栏菜单的方法

		PopupMenu menu = new PopupMenu();

		MenuItem weibo = new MenuItem("weibo");
		weibo.addActionListener(new ActionListener() {// 系统栏打开菜单项事件
					public void actionPerformed(ActionEvent e) {
						openUrl("http://t.qq.com/woshiwzyn");
					}
				});

		MenuItem openItem = new MenuItem("open");
		openItem.addActionListener(new ActionListener() {// 系统栏打开菜单项事件
					public void actionPerformed(ActionEvent e) {
						if (!isVisible()) {
							setVisible(true);
							toFront();
						} else
							toFront();
					}
				});

		MenuItem exitItem = new MenuItem("exit");
		exitItem.addActionListener(new ActionListener() { // 系统栏退出事件
					public void actionPerformed(ActionEvent e) {
						System.exit(0);
					}
				});
		// 系统栏的访问服务器菜单项事件

		menu.add(weibo);
		menu.addSeparator();
		menu.add(openItem);
		menu.addSeparator();
		menu.add(exitItem);

		return menu;
	}

	private void SystemTrayInitial() { // 系统栏初始化
		if (isTray == true) {
			return;
		}
		if (!SystemTray.isSupported()) // 判断当前系统是否支持系统栏
			return;
		try {
			SystemTray sysTray = SystemTray.getSystemTray();
			Image image = Toolkit.getDefaultToolkit().getImage(
					MainFrame.class.getResource("res/icons/icon.png"));// 系统栏图标
			trayicon = new TrayIcon(image, title + "\n" + company, createMenu());
			trayicon.setImageAutoSize(true);
			trayicon.addActionListener(new SysTrayActionListener());
			sysTray.add(trayicon);
			trayicon.displayMessage(title, company, MessageType.INFO);
			isTray = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	class SysTrayActionListener implements ActionListener {// 系统栏双击事件
		public void actionPerformed(ActionEvent e) {
			setVisible(true);
			toFront();
		}
	}

	public static void openUrl(String url) {
		try {
			URI uri = null;
			Desktop desktop = Desktop.getDesktop();
			uri = new URI(url);
			desktop.browse(uri);
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		MainFrame mainFrame = new MainFrame();
	}
}
